/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.asl.member;

import com.hboxs.asl.*;
import com.hboxs.asl.Message;
import com.hboxs.asl.controller.app.member.OrderControl;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.entity.*;
import com.hboxs.asl.entity.Order;
import com.hboxs.asl.entity.Order.PaymentStatus;
import com.hboxs.asl.plugin.PaymentPlugin;
import com.hboxs.asl.service.*;
import com.hboxs.asl.util.SettingUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller - 会员中心 - 订单
 */
@Controller("aslMemberOrderController")
@RequestMapping("/weChat/order")
public class OrderController extends BaseController {

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "areaServiceImpl")
    private AreaService areaService;
    @Resource(name = "receiverServiceImpl")
    private ReceiverService receiverService;
    @Resource(name = "cartServiceImpl")
    private CartService cartService;
    @Resource(name = "paymentMethodServiceImpl")
    private PaymentMethodService paymentMethodService;
    @Resource(name = "shippingMethodServiceImpl")
    private ShippingMethodService shippingMethodService;
    @Resource(name = "couponCodeServiceImpl")
    private CouponCodeService couponCodeService;
    @Resource(name = "orderServiceImpl")
    private OrderService orderService;
    @Resource(name = "shippingServiceImpl")
    private ShippingService shippingService;
    @Resource(name = "pluginServiceImpl")
    private PluginService pluginService;
    @Resource(name = "productServiceImpl")
    private ProductService productService;

    private static final Integer PAY_ORDERS = 0;
    private static final Integer SHIP_ORDERS = 1;
    private static final Integer RETURN_ORDERS = 2;
    private static final Integer EVALUATION_ORDERS = 3;
    private static final Integer ALL_ORDERS = 4;
    private static final Integer RECEIPT_ORDERS = 5;
    private static final Integer CANCEL_ORDERS = 6;


    /**
     * 订单锁定
     *
     * @param sn
     * @return
     */
    @RequestMapping(value = "/lock", method = RequestMethod.POST)
    public
    @ResponseBody
    boolean lock(String sn) {
        Order order = orderService.findBySn(sn);
        if (order != null && memberService.getCurrent().equals(order.getMember()) && !order.isExpired()
                && !order.isLocked(null) && !order.isMerchantLocked(null) && order.getPaymentMethod() != null && order.getPaymentMethod().getMethod() == PaymentMethod.Method.online
                && (order.getPaymentStatus() == PaymentStatus.unpaid || order.getPaymentStatus() == PaymentStatus.partialPayment)) {

            order.setLockExpire(DateUtils.addSeconds(new Date(), 20));
            order.setOperator(null);
            orderService.update(order);
            return true;
        }
        return false;
    }

    /**
     * 检查支付
     *
     * @param sn
     * @return
     */
    @RequestMapping(value = "/check_payment", method = RequestMethod.POST)
    public
    @ResponseBody
    boolean checkPayment(String sn) {
        Order order = orderService.findBySn(sn);
        return order != null && memberService.getCurrent().equals(order.getMember()) && order.getPaymentStatus() == PaymentStatus.paid;
    }

    /**
     * 优惠券信息
     *
     * @param code
     * @return
     */
    @RequestMapping(value = "/coupon_info", method = RequestMethod.POST)
    public
    @ResponseBody
    Map<String, Object> couponInfo(String code) {
        Map<String, Object> data = new HashMap<String, Object>();
        Cart cart = cartService.getCurrent();
        if (cart == null || cart.isEmpty()) {
            data.put("message", Message.warn("shop.order.cartNotEmpty"));
            return data;
        }
        CouponCode couponCode = couponCodeService.findByCode(code);
        if (couponCode != null && couponCode.getCoupon() != null) {
            Coupon coupon = couponCode.getCoupon();
            if (!coupon.getIsEnabled()) {
                data.put("message", Message.warn("shop.order.couponDisabled"));
                return data;
            }
            if (!coupon.hasBegun()) {
                data.put("message", Message.warn("shop.order.couponNotBegin"));
                return data;
            }
            if (coupon.hasExpired()) {
                data.put("message", Message.warn("shop.order.couponHasExpired"));
                return data;
            }
            if (!cart.isValid(coupon)) {
                data.put("message", Message.warn("shop.order.couponInvalid"));
                return data;
            }
            if (couponCode.getIsUsed()) {
                data.put("message", Message.warn("shop.order.couponCodeUsed"));
                return data;
            }
            data.put("message", SUCCESS_MESSAGE);
            data.put("couponName", coupon.getName());
            return data;
        } else {
            data.put("message", Message.warn("shop.order.couponCodeNotExist"));
            return data;
        }
    }

    /**
     * 信息
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public String info(String code, ModelMap model, String payPointJson, Boolean isEncode) {
        // 将json字符串转换成商家order匹配积分
        try {
            if (isEncode != null && isEncode == true && payPointJson != null) {
                payPointJson = java.net.URLDecoder.decode(payPointJson, "utf-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return FZF;
        }

        Map<Long, BigDecimal> order2Point = OrderControl.changeJsonToOrderPoint(payPointJson);

        Member member = memberService.getCurrent();

        Cart cart = cartService.getCurrent();
        if (cart == null || cart.isEmpty()) {
            return FZF;
        }
        if (!isValid(cart)) {
            return FZF;
        }

        Receiver receiver = receiverService.findDefault(memberService.getCurrent());

        List<Order> orders = orderService.build(
                cart, null, null, couponCodeService.findByCode(code), false,
                null, false, new BigDecimal(0), null
        );

        // 自营订单
        Order adminOrder = orderService.build(
                cart, null, null, shippingMethodService.findDefault(), couponCodeService.findByCode(code), false,
                null, false, new BigDecimal(0), null
        );

        if (adminOrder != null) orders.add(adminOrder);

        // 判断当前会员在确认订单上可以使用的积分,1积分当1元使用
        BigDecimal orderTurnToPoint = new BigDecimal(0);
        for (Order order : orders) {
            orderTurnToPoint = orderTurnToPoint.add(order.getAmountPayable().multiply(Constant.POINT_SCALE));
        }

        BigDecimal maxUsablePoint = member.getPoint().compareTo(orderTurnToPoint) <= 0 ? member.getPoint() : orderTurnToPoint;

        // 支付积分不能大于订单金额和用户积分的最小值
        BigDecimal payPoint = new BigDecimal(0);

        if (order2Point != null) {
            for (Long key : order2Point.keySet()) {
                BigDecimal value = order2Point.get(key);
                payPoint = payPoint.add(value);
            }
            if (payPoint.compareTo(maxUsablePoint) > 0) {
                return FZF;
            }
        }

        //用非促销购物车项选择优惠卷,按找减价排序
        BigDecimal couponPrice = cart.getPrice();
        List<CouponCode> couponCodes = couponCodeService.findListByPrice(member, true, false, false, couponPrice);

        model.addAttribute("orders", orders);
        model.addAttribute("receivers", member.getReceivers());
        model.addAttribute("receiver", receiver);
        model.addAttribute("cartToken", cart.getToken());
        model.addAttribute("couponCodes", couponCodes);
        model.addAttribute("maxUsablePoint", maxUsablePoint);
        model.addAttribute("paymentMethods", paymentMethodService.findAll());
        model.addAttribute("shippingMethods", shippingMethodService.findAll());
        return "/yijing/order-detail";
    }

    /**
     * 虚拟订单页面
     */
    @RequestMapping(value = "/updateInfo", method = RequestMethod.GET)
    public
    @ResponseBody
    Object updateInfo(String payPointJson, String code, Boolean isEncode, String memoJson) {

        // 将json字符串转换成商家order匹配积分
        try {
            if (isEncode != null && isEncode == true && payPointJson != null) {
                payPointJson = java.net.URLDecoder.decode(payPointJson, "utf-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return FZF;
        }

        Map<Long, BigDecimal> order2Point = OrderControl.changeJsonToOrderPoint(payPointJson);

        System.out.println(payPointJson);
        System.out.println(order2Point);
        Member member = memberService.getCurrent();
        if (member == null) {
            return JsonMessage.USER_NOT_LOGIN;
        }
        Cart cart = cartService.getCurrent();
        if (cart == null || cart.isEmpty()) {
            return JsonMessage.error("购物车不存在");
        }
        if (!isValid(cart)) {
            return JsonMessage.error("购物车参数非法");
        }
        Receiver receiver = receiverService.findDefault(memberService.getCurrent());
        List<Order> orders = orderService.build(
                cart, null, null, couponCodeService.findByCode(code), false,
                null, false, new BigDecimal(0), null
        );

        // 自营订单
        Order adminOrder = orderService.build(
                cart, null, null, shippingMethodService.findDefault(), couponCodeService.findByCode(code), false,
                null, false, new BigDecimal(0), null
        );
        if (adminOrder != null) orders.add(adminOrder);

        // 判断当前会员在确认订单上可以使用的积分,1积分当1元使用
        BigDecimal orderTurnToPoint = new BigDecimal(0);
        for (Order order : orders) {
            orderTurnToPoint = orderTurnToPoint.add(order.getAmountPayable().multiply(Constant.POINT_SCALE));
        }

        BigDecimal maxUsablePoint = member.getPoint().compareTo(orderTurnToPoint) <= 0 ? member.getPoint() : orderTurnToPoint;

        // 支付积分不能大于订单金额和用户积分的最小值
        BigDecimal payPoint = new BigDecimal(0);

        if (order2Point != null) {
            for (Long key : order2Point.keySet()) {
                BigDecimal value = order2Point.get(key);
                payPoint = payPoint.add(value);
            }
            if (payPoint.compareTo(maxUsablePoint) > 0) {
                return FZF;
            }
        }

        //用非促销购物车项选择优惠卷,按找减价排序
        BigDecimal couponPrice = cart.getPrice();
        List<CouponCode> couponCodes = couponCodeService.findListByPrice(member, true, false, false, couponPrice);

        CouponCode couponCode = null;
        if (code == null) {
            couponCode = couponCodes.size() == 0 ? null : couponCodes.get(0);
        } else {
            couponCode = couponCodeService.findByCode(code);
        }

        if (order2Point != null) {
            List<Merchant> merchants = cart.getMerchants();
            Long merchantId = null;
            for (Order order : orders) {
                if (order.getMerchant() == null) {
                    order.setPayPoint(order2Point.get(0l) == null ? new BigDecimal(0) : order2Point.get(0l));
                } else {
                    merchantId = order.getMerchant().getId();
                    order.setPayPoint(order2Point.get(merchantId) == null ? new BigDecimal(0) : order2Point.get(merchantId));
                }
            }
        }

        BigDecimal totalAmountPayable = new BigDecimal(0);
        for (Order order : orders) {
            totalAmountPayable = totalAmountPayable.add(order.getAmountPayable());
        }

        return JsonMessage.success(

                "maxUsablePoint", maxUsablePoint

                , "totalAmountPayable", totalAmountPayable

        );

    }


    /**
     * 未支付订单详情页面
     *
     * @param sn
     * @param model
     * @return
     */
    @RequestMapping(value = "/pay", method = RequestMethod.GET)
    public String pay(String sn, ModelMap model) {
        try {
            Order order = orderService.findBySn(sn);
            if (order != null) {
                model.addAttribute("order", order);
                return "/yijing/myOrders/order-payment";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }


    /**
     * 未支付订单详情页面
     *
     * @param sn
     * @param model
     * @return
     */
    @RequestMapping(value = "/pay-success", method = RequestMethod.GET)
    public String paySuccess(String sn, ModelMap model) {
        try {
            Order order = orderService.findBySn(sn);
            if (order != null) {
                model.addAttribute("order", order);
                return "/yijing/myOrders/order-payment-success";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }


    /**
     * 创建
     *
     * @param payPointJson 积分{merchant1:paypoint1,merchant2:paypoint2}
     * @param cartToken    购物车
     * @param receiverId   收货地址
     * @param isInvoice    是否开据发票
     * @param code         优惠码
     * @param memoJson     备注{merchant1:memo1,merchant2:memo2}
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public
    @ResponseBody
    Object create(String payPointJson, String cartToken, Long receiverId, @RequestParam(defaultValue = "false") Boolean isInvoice,
                  String code, String invoiceTitle, String memoJson, Boolean isEncode) {
        synchronized (String.valueOf(memberService.getCurrent()).intern()) {


            try {
                if (isEncode != null && isEncode == true && payPointJson != null) {
                    payPointJson = java.net.URLDecoder.decode(payPointJson, "utf-8");
                }
                if (isEncode != null && isEncode == true && memoJson != null) {
                    memoJson = java.net.URLDecoder.decode(memoJson, "utf-8");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            Map<Long, BigDecimal> order2Point = OrderControl.changeJsonToOrderPoint(payPointJson);
            Map<Long, String> merchant2memo = OrderControl.changeJsonToMemo(memoJson);


            Cart cart = cartService.getCurrent();
            if (cart == null || cart.isEmpty()) {
                return JsonMessage.error("购物车不能为空");
            }
            if (!StringUtils.equals(cart.getToken(), cartToken)) {
                return JsonMessage.error("购物车商品已修改，请检查购物车");
            }
            if (cart.getIsLowStock()) {
                return JsonMessage.error("购物车商品库存不足，请修改购物车商品");
            }
            Receiver receiver = receiverService.find(receiverId);
            if (receiver == null) {
                return JsonMessage.error("收货地址不存在");
            }


            // 默认一个微信支付
            List<PaymentMethod> paymentMethods = paymentMethodService.findList(1, null, null);
            if (paymentMethods == null || paymentMethods.size() == 0) {
                return JsonMessage.error("支付方式不存在");
            }
            PaymentMethod paymentMethod = paymentMethods.get(0);
            ShippingMethod shippingMethod = shippingMethodService.findDefault();
            if (shippingMethod == null) {
                return JsonMessage.error("配送方式不存在");
            }

            //检查用户积分是否够用
            BigDecimal payPoint = new BigDecimal(0);
            if (order2Point != null) {
                for (Long key : order2Point.keySet()) {
                    BigDecimal value = order2Point.get(key);
                    payPoint = payPoint.add(value);
                }
                if (payPoint.compareTo(memberService.getCurrent().getPoint()) > 0) {
                    return JsonMessage.error("积分无效");
                }
            }


            CouponCode couponCode = couponCodeService.findByCode(code);

            List<Order> orders = orderService.create(cart, receiver, paymentMethod, shippingMethodService.findDefault(), couponCode,
                    isInvoice, invoiceTitle, false, new BigDecimal(0), merchant2memo, null);

            if (order2Point != null) {
                List<Merchant> merchants = cart.getMerchants();
                Long merchantId = null;
                for (Order order : orders) {
                    if (order.getMerchant() == null) {
                        order.setPayPoint(order2Point.get(0l) == null ? new BigDecimal(0) : order2Point.get(0l));
                    } else {
                        merchantId = order.getMerchant().getId();
                        order.setPayPoint(order2Point.get(merchantId) == null ? new BigDecimal(0) : order2Point.get(merchantId));
                    }
                    orderService.update(order);
                }
            }

            OrderControl.count++;


            return JsonMessage.success(

                    "receiver", JsonMessage.optimiseObj(receiver, "zipCode", "phone", "address", "areaName", "consignee")

                    , "order", JsonMessage.optimiseObj(orders, "sn", "freight", "amountPayable")
            );

        }
    }

    /**
     * 计算支付金额
     *
     * @param paymentPluginId
     * @param sn
     * @return
     */
    @RequestMapping(value = "/calculate_amount", method = RequestMethod.POST)
    public
    @ResponseBody
    Map<String, Object> calculateAmount(String paymentPluginId, String sn) {
        Map<String, Object> data = new HashMap<String, Object>();
        Order order = orderService.findBySn(sn);
        PaymentPlugin paymentPlugin = pluginService.getPaymentPlugin(paymentPluginId);
        if (order == null || !memberService.getCurrent().equals(order.getMember()) || order.isExpired() || order.isLocked(null) || order.getPaymentMethod() == null || order.getPaymentMethod().getMethod() == PaymentMethod.Method.offline || paymentPlugin == null || !paymentPlugin.getIsEnabled()) {
            data.put("message", ERROR_MESSAGE);
            return data;
        }
        data.put("message", SUCCESS_MESSAGE);
        data.put("fee", paymentPlugin.calculateFee(order.getAmountPayable()));
        data.put("amount", paymentPlugin.calculateAmount(order.getAmountPayable()));
        return data;
    }

    /**
     * “全部订单”列表
     *
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = "/orders", method = RequestMethod.GET)
    public String orders(Pageable pageable, ModelMap model) {
        try {
            Member member = memberService.getCurrent();
            Page<Order> page = orderService.findPage(member, pageable, ALL_ORDERS);
            model.addAttribute("orders", page.getContent());
            model.addAttribute("totalPages", page.getTotalPages());
            model.addAttribute("nextPage", page.getPageNumber() + 1);
            return "/yijing/myOrders/orders";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }

    /**
     * 待付款订单列表
     *
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = "/notPaid", method = RequestMethod.GET)
    public String unPayOrders(Pageable pageable, ModelMap model) {
        try {
            Member member = memberService.getCurrent();
            Page<Order> page = orderService.findPage(member, pageable, PAY_ORDERS);
            model.addAttribute("orders", page.getContent());
            model.addAttribute("totalPages", page.getTotalPages());
            model.addAttribute("nextPage", page.getPageNumber() + 1);
            return "/yijing/myOrders/payment";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }


    /**
     * 待发货订单列表
     *
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = "/shipment", method = RequestMethod.GET)
    public String shipment(Pageable pageable, ModelMap model) {
        try {
            Member member = memberService.getCurrent();
            Page<Order> page = orderService.findPage(member, pageable, SHIP_ORDERS);
            model.addAttribute("orders", page.getContent());
            model.addAttribute("totalPages", page.getTotalPages());
            model.addAttribute("nextPage", page.getPageNumber() + 1);
            return "/yijing/myOrders/shipment";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }


    /**
     * 查看各类订单详情
     *
     * @param id
     * @param type
     * @param model
     * @return
     */
    @RequestMapping(value = "/detail", method = RequestMethod.GET)
    public String detail(Long id, Integer type, ModelMap model) {
        try {
            String[] views = {
                    "",
                    "/yijing/myOrders/shipping-detail",
                    "/yijing/myOrders/receipt-detail",
                    "",
                    "",
                    "",
                    "/yijing/myOrders/receipt-detail"};
            Order order = orderService.find(id);
            if (order != null) {
                shippingService.findByOrder(order);
                model.addAttribute("order", order);
                model.addAttribute("shipping", shippingService.findByOrder(order));
                return views[type];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }


    /**
     * 待收货订单列表
     *
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = "/receipt", method = RequestMethod.GET)
    public String receipt(Pageable pageable, ModelMap model) {
        try {
            Member member = memberService.getCurrent();
            Page<Order> page = orderService.findPage(member, pageable, RECEIPT_ORDERS);
            model.addAttribute("orders", page.getContent());
            model.addAttribute("totalPages", page.getTotalPages());
            model.addAttribute("nextPage", page.getPageNumber() + 1);
            return "/yijing/myOrders/receipt";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }

    /**
     * 待评价订单列表
     *
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = "/evaluation", method = RequestMethod.GET)
    public String evaluation(Pageable pageable, ModelMap model) {
        try {
            Member member = memberService.getCurrent();
            Page<Order> page = orderService.findPage(member, pageable, EVALUATION_ORDERS);
            model.addAttribute("orders", page.getContent());
            model.addAttribute("totalPages", page.getTotalPages());
            model.addAttribute("nextPage", page.getPageNumber() + 1);
            return "/yijing/myOrders/evaluation";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }

    /**
     * 退换货订单列表
     *
     * @param pageable
     * @param model
     * @return
     */
    @RequestMapping(value = "/returns", method = RequestMethod.GET)
    public String returns(Pageable pageable, ModelMap model) {
        try {
            Member member = memberService.getCurrent();
            Page<Order> page = orderService.findPage(member, pageable, RETURN_ORDERS);
            model.addAttribute("orders", page.getContent());
            model.addAttribute("totalPages", page.getTotalPages());
            model.addAttribute("nextPage", page.getPageNumber() + 1);
            return "/yijing/myOrders/returns";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/yijing/404";
    }


    /**
     * 我的订单
     *
     * @param status 状态代码:0待支付;1待发货2待收货;3已完成 ;4全部訂單
     * @return json
     */
    @RequestMapping(value = "/page", method = RequestMethod.GET)
    public
    @ResponseBody
    Object list(Pageable pageable, int status) {

        try {
            Member member = memberService.getCurrent();
            if (member == null) {
                return JsonMessage.USER_NOT_LOGIN;
            }

            Page page = orderService.findPage(member, pageable, status);

            return JsonMessage.success(

                    "totalPage", page.getTotalPages()

                    , "pageNumber", page.getPageNumber()

                    , "nextPage", page.getPageNumber() + 1

                    , "pageSize", page.getPageSize()

                    , "total", page.getTotal()

                    , "totalPages", page.getTotalPages()

                    , "content", JsonMessage.optimiseObj(

                            page.getContent(),

                            "id", "sn", "amount", "paymentStatus", "orderStatus", "shippingStatus", "displayStatus",

                            "freight", "orderItems.product.image#product.name#product.specValNames#product.id#quantity#subtotal#price"
                    )
            );

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 确认收货完成订单
     *
     * @param sn 订单号
     * @return json
     */
    @RequestMapping(value = "/complete", method = RequestMethod.POST)
    public
    @ResponseBody
    Object complete(String sn) {
        try {
            Member member = memberService.getCurrent();
            Order order = orderService.findBySn(sn);
            if (order == null) {
                return JsonMessage.error("订单不存在");
            }
            if (!member.getOrders().contains(order)) {
                return JsonMessage.error("订单不属于该会员");
            }
            if (order.isExpired()) {
                return JsonMessage.error("订单已过期");
            }
            if (Order.OrderStatus.confirmed.equals(order.getOrderStatus()) && Order.ShippingStatus.shipped.equals(order.getShippingStatus())) {
                orderService.complete(order, null);
            }
            return JsonMessage.success("已经确认订单，谢谢您的光顾！");

        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 取消订单
     *
     * @param sn
     * @return
     */
    @RequestMapping(value = "/cancel", method = RequestMethod.POST)
    public
    @ResponseBody
    Object cancel(String sn) {
        try {


            Order order = orderService.findBySn(sn);
            if (order != null && memberService.getCurrent().equals(order.getMember()) && !order.isExpired() && /** order.getOrderStatus() == OrderStatus.unconfirmed &&**/order.getPaymentStatus() == PaymentStatus.unpaid) {

                if (order.isLocked(null)) {
                    return Message.warn("shop.member.order.locked");
                }
                orderService.cancel(order, null);
                return JsonMessage.success("关闭成功");
            }
            return JsonMessage.error("关闭失败");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 物流动态
     *
     * @param sn
     * @return
     */
    @RequestMapping(value = "/delivery_query", method = RequestMethod.GET)
    public
    @ResponseBody
    Map<String, Object> deliveryQuery(String sn) {
        Map<String, Object> data = new HashMap<>();
        Shipping shipping = shippingService.findBySn(sn);
        Setting setting = SettingUtils.get();
        if (shipping != null && shipping.getOrder() != null && memberService.getCurrent().equals(shipping.getOrder().getMember()) && StringUtils.isNotEmpty(setting.getKuaidi100Key()) && StringUtils.isNotEmpty(shipping.getDeliveryCorpCode()) && StringUtils.isNotEmpty(shipping.getTrackingNo())) {
            data = shippingService.query(shipping);
        }
        return data;
    }


    /**
     * 请求快递url
     */
    @RequestMapping(value = "/shipping_url", method = RequestMethod.GET)
    public String getShippingUrl(String sn) {
        Order order = orderService.findBySn(sn);
        if (order == null) {
            return FZF;
        }
        String url = shippingService.queryByOrder(order);
        return "redirect:" + url;
    }


}